#include <stdint.h>

#include "vicl.h"

static void VixDiscoveryProc(VixHandle jobHandle,
                             VixEventType eventType,
                             VixHandle moreEventInfo,
                             void *clientData)
{
    err = VIX_OK;
    char *url = NULL;

    // Check callback event; ignore progress reports.
    if (VIX_EVENTTYPE_FIND_ITEM != eventType)
        return;
    
    // Found a virtual machine.
    err = Vix_GetProperties(moreEventInfo,
                            VIX_PROPERTY_FOUND_ITEM_LOCATION,
                            &url,
                            VIX_PROPERTY_NONE);
    if(VIX_OK != err)
    {
        // Handle the error...
        Vix_FreeBuffer(url);
        VICL_ERROR("VixDiscoveryProc failed");
        return;
    }

    vmachine[vmachine_idx].usable = true;
    vmachine[vmachine_idx].path = url;
    vmachine_idx++;
}


int enumerate_virtual_machines(void)
{
    VICL_INFO_RESET();
    vmachine_idx = 0;

    int i;
    for(i = 0; i < MAX_VMS; i++)
        vmachine[i].usable = false;

    jobHandle = VixHost_FindItems(hostHandle,
                                  VIX_FIND_REGISTERED_VMS,
                                  VIX_INVALID_HANDLE, // searchCriteria
                                  -1, // timeout
                                  VixDiscoveryProc,     // call our function handler
                                  NULL);
                                 
    err = VixJob_Wait(jobHandle, VIX_PROPERTY_NONE);
    if(VIX_FAILED(err)) 
    {
        VICL_ERROR("VixHost_FindItems failed\n");
        return -1;
    }

    return 0;
}

int list_virtual_machines(void)
{
    VICL_INFO_RESET();
    
    if(enumerate_virtual_machines() == -1)
        return -1;
    
    int i;
    for(i = 0; i < MAX_VMS; i++)
    {
        if(vmachine[i].usable == true)
        {
            VICL_INFO("[%c]: %s", vmachine_ids[i], vmachine[i].path);
        }
    }
    
    return 0;
}

